<template>
  <div class="blogcategory-container">
    <h2>文章分类</h2>
    <StackContents :list="activeCategoryArr" @click="handlerCategoryActive" />
  </div>
</template>

<script>
import { StackContents } from "./";
import fetchData from "@/mixins/fetchData.js";
import { getBlogCategory } from "@/api/blog";
export default {
  name: "BlogCategory",
  components: {
    StackContents,
  },
  mixins: [fetchData([])],
  computed: {
    categoryId() {
      return +this.$route.params.categoryId || -1;
    },
    limit() {
      return +this.$route.query.limit || 10;
    },

    activeCategoryArr() {
      const totalCategory = this.data.reduce(
        (pre, cur) => pre + cur.articleCount,
        0
      );
      const totalItem = {
        id: -1,
        name: "全部分类",
        articleCount: totalCategory,
      };
      const activeCategoryArr = [totalItem, ...this.data];
      return activeCategoryArr.map((item) => ({
        ...item,
        isActive: item.id == this.categoryId,
      }));
    },
  },
  methods: {
    async fetchData() {
      const res = await getBlogCategory();
      return res.data;
    },
    handlerCategoryActive(item) {
      const query = {
        page: 1,
        limit: this.limit,
      };
      if (item.id == -1) {
        this.$router.push({
          name: "Blog",
          query,
        });
      } else {
        this.$router.push({
          name: "CategoryBlog",
          params: {
            categoryId: item.id,
          },
          query,
        });
      }
    },
  },
};
</script>

<style scoped lang="less">
.blogcategory-container {
  max-width: 300px;
  height: 100%;
  padding: 8px 20px;

  h2 {
    letter-spacing: 2px;
  }
}
</style>
